/*
    C socket server example, handles multiple clients using threads
*/

#include<stdio.h>
#include<string.h>    //strlen
#include<stdlib.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write
#include<pthread.h> //for threading , link with lpthread
#include<iostream> //for threading , link with lpthread

//the thread function
void *connection_handler(void *);

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c , *new_sock;
    struct sockaddr_in server , client;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0); //SOCK_STREAM E pentru conexiune TCP
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 5600 );

    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");

    //Listen
    listen(socket_desc , 3);

    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);


    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");

        pthread_t sniffer_thread;
        new_sock = (int *)malloc(1);
        *new_sock = client_sock;

        if( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)
        {
            perror("could not create thread");
            return 1;
        }

        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( sniffer_thread , NULL);
        puts("Handler assigned");
    }

    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }

    return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
#define MAX_MSG 100
#define LINE_ARRAY_SIZE (MAX_MSG+1)

    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[LINE_ARRAY_SIZE];

    //Send some messages to the client
    message = "Greetings! I am your connection handler\n";
//    write(sock , message , strlen(message));
//
//    message = "Now type something and i shall repeat what you type \n";
//    write(sock , message , strlen(message));

    //Receive a message from client

    memset(client_message, 0x0, LINE_ARRAY_SIZE);

    while( (read_size = recv(sock , client_message , MAX_MSG , 0)) > 0 )
    {
        //Send the message back to client
    	std::string * response = new std::string();
    	response->append("SERVER ANSWER: ");
    	response->append(client_message);
    	message=client_message;
      //  write(sock , response->c_str() , strlen(response->c_str()));
    	char htmlresponse[] = "HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n<h1>Hello, client! Welcome to the Virtual Machine Web..</h1>";
    	//char htmlresponse[] = "HTTP/1.0 200 OK\r\n <h1>Hello, client! Welcome to the Virtual Machine Web..</h1> Server: PGWebServ v0.1\r\n Content-Type: text/html\r\n\r\n";
        //write(sock, client_message, strlen(client_message));
        write(sock, htmlresponse, strlen(htmlresponse));
        std::cout << client_message <<  std::endl;
        //std::cout << client_message <<  std::endl;
    	delete response;
    }

    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    //Free the socket pointer
    free(socket_desc);

    return 0;
}
